package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongdb.VideoApi;
import com.tanhua.domain.UserHolder;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mogo.FollowUser;
import com.tanhua.domain.mogo.Video;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.template.OssTemplate;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoService {

    @Reference
    private VideoApi videoApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //查询小视频
    @Cacheable(value = "video")
    public PageBeanVo smallVideos(Integer page, Integer pagesize) {

        System.out.println("我执行。。。");
        // 分页查询video数据--mongo
        PageBeanVo pageBean = videoApi.findVideo(page, pagesize);
        // 查询userInfo数据
        List<Video> items = (List<Video>) pageBean.getItems();
        List<VideoVo> videoVoList=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(items)){
            for (Video video : items) {
                UserInfo userInfo = userInfoApi.findByUser(video.getUserId());
                // 封装app需要vo
                VideoVo vo = new VideoVo();
                BeanUtils.copyProperties(userInfo,vo);
                vo.setUserId(userInfo.getId());
                BeanUtils.copyProperties(video,vo);
                //视频说明
                vo.setSignature(video.getText());
                vo.setCover(video.getPicUrl());
                if(stringRedisTemplate.hasKey(StrUtil.format("follow_user_{}_{}",UserHolder.findUser().getId(),video.getUserId()))){
                    vo.setHasFocus(1); //是否关注
                }else {
                    vo.setHasFocus(0); //是否关注
                }
                vo.setHasLiked(0); //是否点赞
                videoVoList.add(vo);
            }
        }

        // 返回pageBean
        pageBean.setItems(videoVoList);

        return pageBean;
    }

    //发布小视频+2
    @CacheEvict(value = "video",allEntries = true)
    public ResponseEntity uploadVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        //上传封面记录地址--oss
        String fm_url = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //上传视频记录地址--fastdfs
                //1 文件流  2 文件大小  3 文件后缀名  4 文件属性（null）
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);
        String video_url=webServer.getWebServerUrl()+storePath.getFullPath();
        //创建video封装属性
        Video video = new Video();
        video.setPicUrl(fm_url);
        video.setVideoUrl(video_url);
        video.setUserId(UserHolder.findUser().getId());
        video.setText("震惊~一男子夜奔没穿衣服...");
        //保存
        videoApi.save(video);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity userFocus(Long uid, Long id) {

        //创建实体封装数据
        FollowUser followUser=new FollowUser();
        followUser.setCreated(System.currentTimeMillis());
        followUser.setUserId(id);
        followUser.setFollowUserId(uid);
        videoApi.saveGz(followUser);
        //记录关注信息到redis中  "follow_user_{登录用户}_{小视频作者用户}"
        stringRedisTemplate.opsForValue().set(StrUtil.format("follow_user_{}_{}",id,uid),"1");
        return ResponseEntity.ok(null);
    }

    public ResponseEntity userUnFocus(Long uid, Long id) {

        videoApi.deleteGz(uid,id);

        stringRedisTemplate.delete(StrUtil.format("follow_user_{}_{}",id,uid));

        return ResponseEntity.ok(null);
    }
}
